# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy
from scrapy.contrib.loader.processor import TakeFirst, MapCompose
import urllib


def extract_magnet(k):
    def _e(magent):
        p = parse_magnet(magent)
        return p[k]
    return _e


def parse_magnet(magnet):
    params = magnet[len('magnet:?xt=urn:'):]
    ret = dict()
    ih = True
    for kv in params.split('&'):
        (k, v) = ih and kv.split(':') or kv.split('=')
        if ih:
            ih = False
        v = urllib.unquote(v)
        if k in ret:
            if isinstance(ret[k], basestring):
                l = [ret[k]]
            else:
                l = list(ret[k])
            l.append(v)
            ret[k] = l
        else:
            ret[k] = v
    return ret


class Torrent(scrapy.Item):
    name = scrapy.Field(
        input_processor=MapCompose(extract_magnet("dn")),
        output_processor=TakeFirst()
    )
    url = scrapy.Field(
        output_processor=TakeFirst()
    )
    info_hash = scrapy.Field(
        input_processor=MapCompose(extract_magnet("btih")),
        output_processor=TakeFirst()
    )
    magnet_link = scrapy.Field(
        output_processor=TakeFirst()
    )
    tags = scrapy.Field()

    origin = scrapy.Field()
